package com.copa.l209;

/**
 * @author copa
 * @createDate 2022-05-26 11:01
 * @function 滑动窗口法(双指针法)
 */
public class Test2 {

    public int minSubArrayLen(int target, int[] nums) {
        int left = 0;
        int right = 0;
        int result = nums.length + 1;
        int temp = 0;
        while (right < nums.length) {
            temp += nums[right];
            right++;
            while (temp >= target) {
                result = Math.min(result, right - left);
                temp -= nums[left++];
            }
        }
        return result == nums.length + 1 ? 0 : result;
    }

    /**
     * 以下就是我自己做的，感觉看起来复杂化了...虽然是通过了
     * @param target
     * @param nums
     * @return
     */
    public int minSubArrayLen2(int target, int[] nums) {
        int left = 0;
        int right = 0;
        int result = Integer.MAX_VALUE;
        int temp = nums[left];
        while (right != nums.length) {
            if (temp >= target) {
                result = Math.min(result, right - left + 1);
                temp -= nums[left++];
            } else {
                if (right + 1 == nums.length) {
                    break;
                }
                temp += nums[++right];
            }
        }
        return result == Integer.MAX_VALUE ? 0 : result;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{2,3,1,2,4,3};
        //int[] nums = new int[]{1,1,1,1,1,1,1,1};
        int result = new Test2().minSubArrayLen(7, nums);
        System.out.println(result);
    }
}
